package com.marvels.approve.loan.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.dragon.app.ykd.constant.ApplyNode;
import com.dragon.app.ykd.service.AcLoanApplyNodeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.marvels.approve.common.service.McamLoanApplyInfoCommonService;
import com.marvels.approve.loan.dao.IMcamLoanApplyInfoDao;
import com.marvels.approve.loan.dao.McamLoanInsurancePolicyInfoMapper;
import com.marvels.approve.loan.dto.McamAcLoanApplyBdInfo;
import com.marvels.approve.loan.dto.McamAcLoanApplyImageInfo;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.loan.service.DecisionService;
import com.marvels.approve.loan.service.IMcamLoanApplyInfoService;
import com.marvels.approve.mqueues.dto.LoanApplyQueueDTO;
import com.marvels.approve.mqueues.service.ApproveILoanApplyDataSynchronizeService;
import com.marvels.approve.mqueues.service.ApproveILoanApplyMqProduct;
import com.marvels.approve.mqueues.service.ApproveILoanApplyQueueService;
import com.marvels.approve.process.dao.AttachmentInfoDao;
import com.marvels.approve.process.dto.LoanApplyCaseDTO;
import com.marvels.approve.process.service.ILoanApplyCaseService;
import com.marvels.common.constants.LoanCaseStatusConstant;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.SynLoanStatus2ApplyDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;

import net.sf.ezmorph.array.BooleanObjectArrayMorpher;
@Service
public class McamLoanApplyInfoServiceImpl implements IMcamLoanApplyInfoService {

	@Autowired
	private IMcamLoanApplyInfoDao mcamLoanApplyInfoDao ;
	
	@Autowired
	private ApproveILoanApplyDataSynchronizeService loanApplyDataSynchronizeService;
	
	@Autowired
	private ApproveILoanApplyQueueService loanApplyQueueService;
	
	@Autowired
	private ILoanApplyCaseService loanApplyCaseService;
	
	@Autowired
	private McamLoanInsurancePolicyInfoMapper mcamLoanInsurancePolicyInfoMapper;
	
	@Autowired
	private AttachmentInfoDao  AttachmentInfoMapper;
	@Autowired
	private ApproveILoanApplyMqProduct loanApplyMqProduct;
	@Autowired
	private McamLoanApplyInfoCommonService mcamLoanApplyInfoCommonService;
	@Autowired
	private AcLoanApplyNodeService acLoanApplyNodeService;
	
	@Value("${config.properties.path}")
	private  String configPropertiesPath;
	
	@Autowired
	private DecisionService decisionService;
	
	@Override
	public List<McamLoanApplyInfoDTO> findLoanApplys(McamLoanApplyInfoDTO dto) throws MarvelsBusinessException {
		// TODO 自动生成的方法存根
		PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
		return mcamLoanApplyInfoDao.select(dto);
	}
	
	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	public Integer saveMcamLoanApplyInfo(McamLoanApplyInfoDTO apply) throws MarvelsBusinessException {
		// TODO 自动生成的方法存根
		if(apply==null || apply.getLoanId()==null) {
			throw new MarvelsBusinessException("贷款数据为空无法更新查询");
		}
		McamLoanApplyInfoDTO dbInfo = this.mcamLoanApplyInfoDao.selectMcamLoanApplyInfoByLoanId(apply.getLoanId());
		if(dbInfo!=null) {
			MarvelsLogUtil.getInstance().info(dbInfo.getLoanId()+"贷款数据已经存在不能新增");
			return 0;
		}else {
//			apply.setStatus(LoanStateConstant.J00);
			return this.mcamLoanApplyInfoDao.insertByLoanApplyInfo(apply);
		}
	}
	

	@Override
	public McamLoanApplyInfoDTO findMcamLoanApplyInfo(String loanId) throws MarvelsBusinessException {
		// 通过loanId查询
		return this.mcamLoanApplyInfoDao.selectMcamLoanApplyInfoByLoanId(loanId);
	}
	
	@Transactional(timeout = 60 ,rollbackFor=Exception.class)
	@Override
	public boolean initProcessData(LoanApplyQueueDTO loanApplyQueue) throws MarvelsBusinessException {
		//初始化数据并跑决策
		//处理内容
		String loanId = loanApplyQueue.getLoanId();
		// 1\获取进件内容
		McamLoanApplyInfoDTO originalLoan = loanApplyDataSynchronizeService.synchronizeLoanApplyInfo(loanId);
//		 2\获取保单内容
		// loanApplyDataSynchronizeService.synchronizeInsurancePolicy(loanId);
		// 3、获取影像文件
		loanApplyDataSynchronizeService.synchronizeAttachment(loanId);
		//4.同步联系人信息
		loanApplyDataSynchronizeService.synchronizeLinkman(loanId);
		 //自动审核
		boolean decisionResult = decisionService.doDecision(originalLoan);
		// 完成处理
		loanApplyQueue.setStatus(1);
		loanApplyQueueService.editLoanApplyQueueService(loanApplyQueue);
		McamLoanApplyInfoDTO loanApplyInfo = findMcamLoanApplyInfo(loanId);// 查询进件信息
		// 老客户决策不通过不进行拒绝
		Integer loanNumber = mcamLoanApplyInfoDao.querySettleLoan(loanApplyInfo.getCustCardNo());
		MarvelsLogUtil.getInstance().info(loanId + "自动审批决策结果：" + decisionResult + "，老单个数：" + loanNumber);
		if(decisionResult || loanNumber > 0){
			// 进入流程
			String status = loanApplyCaseService.startFlow(loanApplyInfo); //增加case表数据     loanApplyInfo.setStatus("Z00");
			// 保存
			loanApplyInfo.setStatus(status);
			Integer count = updateMcamLoanApplyInfoByLoanId(loanApplyInfo);
			String acLoanStatusFundList=ServerProperties.getValue(configPropertiesPath, "resource.properties", "acLoanStatus.fund.list");
			String acLoanStatusProductList=ServerProperties.getValue(configPropertiesPath, "resource.properties", "acLoanStatus.product.list");
			if(count > 0 && (StringUtil.isEmpty(acLoanStatusFundList) || acLoanStatusFundList.indexOf(","+originalLoan.getFundCode()+",")==-1) && (StringUtil.isEmpty(acLoanStatusProductList) || acLoanStatusProductList.indexOf(","+originalLoan.getProductType()+",")==-1) ) {//占时停止//占时停止
				SynLoanStatus2ApplyDTO synStatus = new SynLoanStatus2ApplyDTO();
				synStatus.setLoanId(loanId);
				synStatus.setStatus(status);
				synStatus.setOriginalState(originalLoan.getStatus());
				loanApplyMqProduct.synLoanStatus2Apply(synStatus);
			}
			MarvelsLogUtil.getInstance().info("跑决策等处理成功,成功进入流程:" + loanId);
		}else{
			// 保存
			loanApplyInfo.setStatus(LoanStateConstant.SR4);
			Integer count = updateMcamLoanApplyInfoByLoanId(loanApplyInfo);
			if(count > 0){
				SynLoanStatus2ApplyDTO synStatus = new SynLoanStatus2ApplyDTO();
				synStatus.setLoanId(loanId);
				synStatus.setStatus(LoanStateConstant.SR4);
				synStatus.setOriginalState(originalLoan.getStatus());
				loanApplyMqProduct.synLoanStatus2Apply(synStatus);
				acLoanApplyNodeService.insertSelective(loanId, ApplyNode.DECISION_REFUSE);
			}
			MarvelsLogUtil.getInstance().info("跑决策自动拒绝:" + loanId);
		}
		return true;
	}
	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	@Override
	public Integer updateMcamLoanApplyInfoByLoanId(McamLoanApplyInfoDTO apply) throws MarvelsBusinessException {
		// TODO Auto-generated method stub
		if(apply==null || apply.getLoanId()==null) {
			throw new MarvelsBusinessException("贷款数据为空无法更新查询");
		}
		int n = this.mcamLoanApplyInfoDao.updateByLoanId(apply);
		if(n < 1) {
			throw new MarvelsBusinessException("贷款数据为空无法更新查询loanId:"+apply.getLoanId());
		}
		return n;
	}
	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	@Override
	public Integer saveMcamPolicyInfo(McamAcLoanApplyBdInfo apply) throws MarvelsBusinessException {
		// TODO 自动生成的方法存根
		if(apply==null || apply.getLoanId()==null) {
			throw new MarvelsBusinessException("保单数据为空无法更新查询");
		}
		return this.mcamLoanInsurancePolicyInfoMapper.insertInsurancePolicy(apply);
	}
	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	@Override
	public Integer saveMcamAttachmentInfo(McamAcLoanApplyImageInfo apply) throws MarvelsBusinessException {
		// TODO 自动生成的方法存根
		if(apply==null || apply.getLoanId()==null) {
			throw new MarvelsBusinessException("映像数据为空无法更新查询");
		}
		return this.AttachmentInfoMapper.insertAttachmentInfo(apply);
	}

	@Override
	public void loanFallback(McamLoanApplyInfoDTO dto) throws MarvelsBusinessException {
		//退回补件
		MarvelsLogUtil.getInstance().info("退回补件dto.getLoanId():"+(dto==null?dto:dto.getLoanId()));
		if(dto == null || StringUtils.isEmpty(dto.getLoanId())) {
			throw new MarvelsBusinessException("参数错误");
		}
		String loanId = dto.getLoanId();
		McamLoanApplyInfoDTO loanApply = this.mcamLoanApplyInfoDao.selectMcamLoanApplyInfoByLoanId(loanId);
		LoanApplyCaseDTO loanCase = loanApplyCaseService.findLoanApplyCase(loanId);
		if(loanApply == null || loanCase == null) {
			throw new MarvelsBusinessException("参数错误");
		}
		String status = loanApply.getStatus();
		MarvelsLogUtil.getInstance().info("退回补件loanId:"+loanId+",status:"+status+"{"+(LoanStateConstant.Z82.equals(status))+"}"+"{"+(LoanStateConstant.Z81.equals(status))+"}");
		if (LoanStateConstant.Z82.equals(status)) {
			loanApply.setStatus(LoanStateConstant.J07);
//			mcamLoanApplyInfoDao.updateApplyInfo(loanApply);
			int count = mcamLoanApplyInfoCommonService.updateMcamLoanApplyInfoStatusByLoanId(loanId,LoanStateConstant.J07, null, MarvelsConstant.SYSTEM_USER);
			if (count>0) {
				loanCase.setCaseStatus(LoanCaseStatusConstant.BJCT);
				loanCase.setCaseType(1);
				loanApplyCaseService.saveLoanApplyCase(loanCase);
			}
		} else if (LoanStateConstant.Z81.equals(status)) {
			loanApply.setStatus(LoanStateConstant.Z01);
			int count = mcamLoanApplyInfoCommonService.updateMcamLoanApplyInfoStatusByLoanId(loanId,LoanStateConstant.Z01, null, MarvelsConstant.SYSTEM_USER);
			if (count>0) {
				loanCase.setCaseStatus(LoanCaseStatusConstant.BJCT);
				loanCase.setCaseType(1);
				loanApplyCaseService.saveLoanApplyCase(loanCase);
			}
		}
	}

	@Override
	public boolean executeDecision(String loanId) throws MarvelsBusinessException {
		return false;
	}

}
